#!/usr/bin/python3

import threading
import os, time
import requests, json
import datetime
from iClouds.web import hasTasksRequest, syncRequest
import logging


def beijing(sec, what):
    beijing_time = datetime.datetime.now() + datetime.timedelta(hours=8)
    return beijing_time.timetuple()


logging.Formatter.converter = beijing

logger = logging.getLogger(__name__)
logger.setLevel(level=logging.INFO)
handler = logging.FileHandler(f"../logs/lipsync.log")
handler.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
# formatter.converter = beijing
handler.setFormatter(formatter)
logger.addHandler(handler)

def hasConf():
    """获取用户配置"""
    try:
        with open("conf.json", "r") as fs:
            return json.load(fs)
    except:
        return {}


CONF = hasConf()
if not CONF:
    logger.error("请先配置conf.json")
    raise Exception("请先配置conf.json")

class myThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.is_Run = True
        self.web = hasTasksRequest(CONF.get("host"))
        self.sync = syncRequest()
        self.max = 3
        self.pool = []
    def stop(self):
        self.is_Run = False

    def run(self):
        print("myThread Thread is running...")
        logger.info("myThread Thread is running...")
        while self.is_Run:
            # 唇同步 13
            time.sleep(3)
            # if len(self.pool) >= self.max: continue
            task = self.web.has_tasksC().get("resmsg")
            if not task: continue
            logger.info(f'新的任务: {task}') 
            res = self.sync.postLipsync(
                **{
                    "audio": task["audio"],
                    "video": task["video"],
                }               
            )
            logger.info(f'任务返回: {task["id"]} {res}')   
            if res.get("id"):
                code, data = 200,res.get("id")                
            elif res.get("statusCode"):
                code, data = 400,res.get("message")   
            else:
                code, data = 500,"未知错误"                           
            self.web.post_task_refer(
                task["guid"],
                "1111",             
                code,
                data,
                task["model"],
                "Lipsync"              
            )
        logger.error("myThread Thread is stoped...")   
         
def hello():
    print(
        """
        Lipsync 合成  ver:1.0             
        """
    )
    print(f'{"x"*40}')
    [print(k, ": ", v) for k, v in CONF.items()]
    print(f'{"x"*40}\n')   
     
if __name__ == "__main__":
    print("Hello")
    main = myThread()
    main.start()    
    while True:
        hello()
        cmd = input(">")
        if cmd in ["q","e","quit","exit","stop"]:
            main.stop()
            break    